﻿(function () {
    "use strict";

    var cardInfo;
    var color;
    var orientation;
    var layout = {};

    function showControl() {
        var _container = $('#colors'), _item, i, bg;

        function change(event) {
            if (event.data.c) {
                color = event.data.c;
                $("#colors > div").removeClass('selected');
            }
            else if (event.data.o) {
                orientation = event.data.o;
                $("#orientations > div").removeClass('selected');
            }

            $(this).addClass('selected');
            showCard();
        }

        _container.empty();
        for (i = 0; i < cardInfo.colors.length; i++) {
            _item = $('<div></div>');
            bg = cardInfo.colors[i] == 'Multicolor' ? 'black' : cardInfo.colors[i];
            _item.css('background-color', bg);
            if (cardInfo.colors[i] == color) {
                _item.addClass('selected');
            }
            _item.click({ c: cardInfo.colors[i] }, change);
            _container.append(_item);
        }

        _container = $('#orientations');
        _container.empty();
        for (i = 0; i < cardInfo.orientations.length; i++) {
            _item = $('<div></div>');
            _item.addClass('icon-' + cardInfo.orientations[i]);
            if (cardInfo.orientations[i] == orientation) {
                _item.addClass('selected');
            }
            _item.click({ o: cardInfo.orientations[i] }, change);
            _container.append(_item);
        }

        $('#control button').click(function () {
            Context.layout = layout;
            WinJS.Navigation.navigate("/pages/preview/preview.html");
        });
    }

    var prefixes = {
        photo: 'userphoto',
        text: 'usertext'
    };

    function getColor(str) {
        var _tokens = str.split('_');

        if (_tokens.length == 1) {
            return str;
        }
        else if (_tokens.length == 3) {
            return 'rgb(' + _tokens[0] + ', ' + _tokens[0] + ', ' + _tokens[0] + ')';
        }
        return '0x000000';
    }

    function getBox(layout, count, type) {
        type = type || 'photo'
        var _result = {}, cx, cy, r, _p = prefixes[type];

        _result.width = parseInt(layout[_p + count + '_box_width']);
        if (isNaN(_result.width)) {
            return;
        }

        _result.width = _result.width;

        _result.height = parseInt(layout[_p + count + '_box_height']);

        _result.left = parseInt(layout[_p + count + '_x']);
        _result.top = parseInt(layout[_p + count + '_y']);

        if (isNaN(_result.left)) {
            cx = parseInt(layout[_p + count + '_center_x']);
            cy = parseInt(layout[_p + count + '_center_y']);
            _result.left = cx - _result.width / 2;
            _result.top = cy - _result.height / 2;
        }

        if (type == 'text') {
            _result['font-family'] = layout[_p + count + '_font_name'];
            _result['font-size'] = parseInt(layout[_p + count + '_font_size']);
            _result['font-min-size'] = parseInt(layout[_p + count + '_font_min_size']);
            _result['color'] = getColor(layout[_p + count + '_fg_color']);
        }

        return _result;
    }

    function analyseLayout(config) {
        var i = 0, _photo, _text;
        layout.width = parseInt(config.layout['montage_box_width']);
        layout.height = parseInt(config.layout['montage_box_height']);
        layout.r = orientation == 'landscape' ? layout.width / 700 : layout.width / 500;
        layout.url = config.document_root + '/' + config.layout.overlay_ipath_print_res;

        layout.photos = [];
        while (true) {
            _photo = getBox(config.layout, i + 10, 'photo');
            if (_photo) {
                _photo.img = Context.photos[i];
                layout.photos.push(_photo);
            }
            else {
                break;
            }
            i++;
        }

        layout.texts = [];
        i = 0;
        while (true) {
            _text = getBox(config.layout, i + 10, 'text');
            if (_text) {
                _text.value = 'Add some message here!';
                layout.texts.push(_text);
            }
            else {
                break;
            }
            i++;
        }
    }

    function adjustCss(css, rate) {
        var _result = {}, p;
        for (p in css) {
            if (typeof css[p] == 'number') {
                _result[p] = css[p] / rate;
            }
            else {
                _result[p] = css[p];
            }
        }
        return _result;
    }

    function drawPhoto(container, photo) {
        if (photo.width / photo.height > photo.img.width / photo.img.height) {
            photo.img.el.attr('class', 'tooHigh');
        }
        else {
            photo.img.el.attr('class', 'tooWide');
        }
        container.append(photo.img.el);
    }

    function drawCard() {
        var _container = $('#card');
        _container.attr('class', orientation);
        _container.empty();
        if (Context.frames[layout.url]) {
            _container.append(Context.frames[layout.url]);
        }
        else {
            _container.append('<img src="' + layout.url + '" />');
        }

        var i, _photo, _text;
        for (i = 0; i < layout.photos.length; i++) {
            _photo  = $('<div class="window"></div>');
            _photo.css(adjustCss(layout.photos[i], layout.r));

            drawPhoto(_photo, layout.photos[i]);

            _container.append(_photo);
        }

        for (i = 0; i < layout.texts.length; i++) {
            _text = $('<p class="text"></p>');
            _text.text(layout.texts[i].value);
            _text.css(adjustCss(layout.texts[i], layout.r));
            _container.append(_text);
        }
    }

    function showCard() {

        analyseLayout(cardInfo.config_map[orientation][color]);
        drawCard();
    }

    WinJS.UI.Pages.define("/pages/card/card.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            // TODO: Initialize the page here.
            cardInfo = Context.cardInfo;
            color = cardInfo.colors[0];
            orientation = cardInfo.orientations[0];
            showControl();
            showCard();
        }
    });
})();
